import { Component, OnInit } from "@angular/core";
import { NzMessageService, NzModalService } from "ng-zorro-antd";
import { FileImportHttpService } from "../services/file-import.service";
import { HttpClient, HttpHeaders } from "@angular/common/http";

@Component({
  selector: "app-file-download",
  templateUrl: "./file-download.component.html",
  styleUrls: ["./file-download.component.less"],
})
export class FileDownloadComponent implements OnInit {
  data = {
    fileType: "fileType",
  };

  constructor(
    private msg: NzMessageService,
    private http: FileImportHttpService,
    private httpDownload: HttpClient,
  ) {}
  radioValue = "";
  fileList = [];
  showDownload = false;

  ngOnInit() {}

  getFileList() {
    this.showDownload = false;
    this.http.getFileAllName().subscribe(
      (res) => {
        if (res.data && res.data.length) {
          this.showDownload = true;
          res.data.map((item, index) => {
            this.fileList.push({
              label: item,
              value: item,
            });
            // this.exportPyc(data.fileType, item);
          });
        } else {
          this.msg.error("数据获取异常");
        }
      },
      (error) => {
        this.msg.error("数据获取异常");
      },
    );
  }

  selectDownloadFile() {
    this.exportPyc(this.data.fileType, this.radioValue);
  }

  // 后端响应头Content-Disposition包含filename，content-disposition：attachment;filename=application_1753171029279_0004.log
  exportPyc(fileType, file_name) {
    const baseUrl = "http://localhost:3000/api/fileDownload/fileDownload";
    const url = `${baseUrl}?fileType=${fileType}&file_name=${file_name}`;
    this.httpDownload
      .get(url, {
        responseType: "blob",
        observe: "response",
        headers: new HttpHeaders().append("Content-Type", "application/json"),
      })
      .subscribe((resp) => {
        const contentDisposition = resp.headers.get("Content-Disposition");
        let fileName;
        if (contentDisposition) {
          const match = contentDisposition.match(/filename=([^;]+)/);
          fileName = match ? match[1] : "default_filename.log";
        } else {
          fileName = "defeat" + ".log";
        }
        this.downloadFile(resp.body, fileName);
      });
  }

  // exportPyc(fileType, file_name) {
  //   const baseUrl = "http://localhost:3000/api/fileDownload/fileDownload";
  //   const url = `${baseUrl}?fileType=${fileType}&file_name=${file_name}`;
  //   this.httpDownload
  //     .get(url, {
  //       responseType: "blob",
  //       headers: new HttpHeaders().append("Content-Type", "application/json"),
  //     })
  //     .subscribe((resp) => {
  //       // resp: 文件流
  //       this.downloadFile(resp, file_name);
  //     });
  // }

  downloadFile(data: BlobPart, file_name: string) {
    const blobType = "application/octet-stream";
    const blob = new Blob([data], { type: blobType });
    const url = window.URL.createObjectURL(blob);
    // 打开新窗口方式进行下载
    // window.open(url);
    // 以动态创建a标签进行下载
    const link = document.createElement("a");
    const fileName = file_name;
    link.href = url;
    link.download = fileName;
    link.click();
    window.URL.revokeObjectURL(url);
  }

  aLinkDownload() {
    const baseUrl = "http://localhost:3000/api/fileDownload/fileDownload";
    const url = `${baseUrl}?fileType=${this.data.fileType}&file_name=${this.radioValue}`;
    window.open(url);
  }
}
